<template>
    <view class="pages" :class="themeName">
        <view class="login">
            <image class="logo" :src="appConfig.logo" mode="heightFix"></image>
            <view class="acount-login">
                <view class="input">
                    <u-field
                        label-width="0"
                        v-model="account"
                        placeholder="请输入手机号"
                        :input-border="false"
                    />
                </view>
                <view class="input">
                    <u-field
                        v-if="loginType == 1"
                        label-width="0"
                        v-model="password"
                        type="password"
                        :password-icon="false"
                        placeholder="请输入密码"
                        :input-border="false"
                    >
                        <view class="forget-btn p-l-20" slot="right">
                            <router-link to="/pages/forget_pwd/forget_pwd">
                                忘记密码
                            </router-link>
                        </view>
                    </u-field>
                    <u-field
                        v-if="loginType == 2"
                        label-width="0"
                        v-model="code"
                        placeholder="请输入验证码"
                        :input-border="false"
                    >
                        <view slot="right">
                            <view class="sms-btn" @tap="sendSMS">
                                <!-- 获取验证码 -->
                                <u-verification-code
                                    unique-key="login"
                                    ref="uCode"
                                    @change="codeChange"
                                >
                                </u-verification-code>
                                <view class="xs">{{ codeTips }}</view>
                            </view>
                        </view>
                    </u-field>
                </view>
                <button class="login-btn white br60" size="lg" @tap="loginFun">
                    登录
                </button>
                <view class="flex row-between">
                    <view>
                        <view
                            class="lighter"
                            v-if="hasLoginWay(1) && loginType == 2"
                            @tap="changeLoginType"
                            >手机号密码登录
                        </view>
                        <view
                            class="lighter"
                            v-if="hasLoginWay(2) && loginType == 1"
                            @tap="changeLoginType"
                            >短信验证码登录
                        </view>
                    </view>
                    <router-link
                        class="lighter"
                        to="/pages/register/register"
                        v-if="isPhoneRegister"
                    >
                        注册账号
                    </router-link>
                </view>
            </view>
            <view class="other-login flex-col flex-1">
                <view class="flex-1 wx-login">
                    <!-- #ifdef MP-WEIXIN -->
                    <view v-if="isMnpWxAuth">
                        <u-divider>其他登录方式</u-divider>
                        <view class="inline" @tap="mnpLogin">
                            <image
                                class="image"
                                src="/static/images/icon_wechat.png"
                            ></image>
                            <view class="sm">微信登录</view>
                        </view>
                    </view>
                    <!-- #endif -->
                    <!-- #ifdef H5 -->
                    <view v-if="isOaWxAuth && isWeixin">
                        <u-divider>其他登录方式</u-divider>
                        <view class="inline" @tap="getCodeUrl">
                            <image
                                class="image"
                                src="/static/images/icon_wechat.png"
                            ></image>
                            <view class="sm">微信登录</view>
                        </view>
                    </view>
                    <!-- #endif -->
                    <!-- #ifdef APP-PLUS -->
                    <!-- #endif -->
                    <!-- #ifdef MP-TOUTIAO -->
                    <view v-if="isToutiaoAuth">
                        <u-divider>其他登录方式</u-divider>
                        <view class="inline" @tap="ttLogin">
                            <image
                                class="image"
                                src="/static/images/icon_toutiao.png"
                            ></image>
                            <view class="sm">字节登录</view>
                        </view>
                    </view>
                    <!-- #endif  -->
                </view>

                <view class="m-b-40 sm flex row-center">
                    已阅读并同意
                    <router-link
                        data-theme=""
                        to="/bundle/pages/server_explan/server_explan?type=1"
                    >
                        <view class="agreement">《服务协议》</view>
                    </router-link>
                    和
                    <router-link
                        to="/bundle/pages/server_explan/server_explan?type=2"
                    >
                        <view class="agreement">《隐私协议》</view>
                    </router-link>
                </view>
            </view>
        </view>
        <!-- #ifdef MP-WEIXIN -->
        <mplogin-popup
            v-model="showLoginPop"
            :logo="appConfig.logo"
            :title="appConfig.shop_name"
            :login-data="loginData"
            @close="closePopup"
            @update="handleSubmitInfo"
        />
        <!--  #endif -->
    </view>
</template>

<script>
import { mapMutations, mapActions, mapGetters } from "vuex";
import {
    apiAuthLogin,
    apiAccountLogin,
    apiLoginCaptcha,
    apiToutiaoAuthLogin,
    apiAppWxLogin,
    apiUpdateUser,
} from "@/api/app";
import wechath5 from "@/utils/wechath5";
import { isWeixinClient, currentPage, client, trottle } from "@/utils/tools";
import Cache from "@/utils/cache";
import { BACK_URL, INVITE_CODE } from "@/config/cachekey";
import { getCode, getUserProfile } from "@/utils/login";
const loginType = {
    ACCOUNT: 1,
    SMS_CODE: 2,
};
export default {
    data() {
        return {
            password: "",
            account: "",
            code: "",
            loginType: "",
            isWeixin: "",
            codeTips: "",
            showLoginPop: false,
            loginData: {},
        };
    },

    methods: {
        ...mapMutations(["login"]),
        ...mapActions(["getUser"]),
        // 小程序微信登录
        async mnpLogin() {
            const {
                userInfo: { avatarUrl, nickName, gender },
            } = await getUserProfile();
            uni.showLoading({
                title: "登录中...",
                mask: true,
            });
            const wxCode = await getCode();
            const data = await apiAuthLogin({
                code: wxCode,
                nickname: nickName,
                headimgurl: avatarUrl,
            });
            if (data.is_new_user) {
                uni.hideLoading();
                this.showLoginPop = true;
                this.loginData = data;
            } else {
                this.loginHandle(data);
            }
            // this.loginHandle(data)
        },
        getCodeUrl() {
            wechath5.getWxUrl();
        },
        // 公众号微信登录
        async oaLogin(code) {
            if (!code) return;
            const data = await wechath5.authLogin(code);
            this.loginHandle(data);
        },
        oaAutoLogin() {
            // H5微信登录
            const { code } = this.$Route.query;
            this.isWeixin = isWeixinClient();
            if (this.isLogin) {
                // 已经登录 => 首页
                uni.switchTab({
                    url: "/pages/index/index",
                });
                return;
            }
            if (code) {
                // 带有code => 登录
                return this.oaLogin(code);
            }
            if (this.isWeixin && this.isOaWxAutoLogin) {
                // 开启自动授权登录
                this.getCodeUrl();
            }
        },
        // app微信登录
        async appLogin() {
            uni.login({
                provider: "weixin",
                success: (res) => {
                    uni.showLoading({
                        title: "登录中...",
                        mask: true,
                    });
                    const { openid, access_token } = res.authResult;
                    apiAppWxLogin({
                        openid,
                        access_token,
                    })
                        .then((res) => {
                            this.loginHandle(res);
                        })
                        .finally((res) => {
                            uni.hideLoading();
                        });
                },
            });
        },
        // 账号登录
        async loginFun() {
            const { account, password, telephone, code, loginType } = this;
            if (!account) {
                this.$toast({
                    title: "请输入手机号",
                });
                return;
            }

            if (this.loginType == 1 && !password) {
                this.$toast({
                    title: "请输入密码",
                });
                return;
            }
            if (this.loginType == 2 && !code) {
                this.$toast({
                    title: "请输入验证码",
                });
                return;
            }

            apiAccountLogin({
                scene: loginType,
                account,
                password: loginType == 1 ? password : "",
                code: loginType == 2 ? code : "",
            }).then((res) => {
                this.loginHandle(res);
            });
        },
        // 登录结果处理
        async loginHandle(data) {
            this.login(data);
            this.getUser();
            // 更新购物车
            this.$store.dispatch("getCartNum");
            uni.hideLoading();
            if (this.isBindMobile && !data.mobile) {
                return this.$Router.replace("/pages/bind_mobile/bind_mobile");
            }
            this.goBack();
        },
        goBack() {
            if (getCurrentPages().length > 1) {
                this.$Router.back(1, {
                    success: () => {
                        const { onLoad, options } = currentPage();
                        // 刷新上一个页面
                        onLoad && onLoad(options);
                    },
                });
            } else if (Cache.get(BACK_URL)) {
                this.$Router.replace(Cache.get(BACK_URL));
            } else {
                this.$Router.replaceAll("/pages/index/index");
            }
            Cache.remove(BACK_URL);
        },
        changeLoginType() {
            if (this.loginType == loginType.ACCOUNT) {
                this.loginType = loginType.SMS_CODE;
            } else if (this.loginType == loginType.SMS_CODE) {
                this.loginType = loginType.ACCOUNT;
            }
        },
        // 发送验证码
        sendSMS() {
            if (!this.$refs.uCode.canGetCode) return;
            if (!this.account) {
                this.$toast({
                    title: "请输入手机号",
                });
                return;
            }
            apiLoginCaptcha({
                mobile: this.account,
            }).then((res) => {
                this.$refs.uCode.start();
            });
        },

        codeChange(tip) {
            this.codeTips = tip;
        },
        // 头条小程序登录
        async ttLogin() {
            const code = await getCode();
            const [err, res] = await uni.getUserInfo();
            if (!res) {
                this.openSetting();
                return;
            }
            const { avatarUrl, nickName } = res.userInfo;
            uni.showLoading({
                title: "登录中...",
            });

            apiToutiaoAuthLogin({
                code,
                avatarUrl,
                nickName,
            })
                .then((res) => {
                    this.loginHandle(res);
                })
                .catch((res) => {
                    console.log(res);
                    uni.hideLoading();
                });
        },
        openSetting() {
            uni.showModal({
                title: "温馨提示",
                content: "您已拒绝授权，是否前往设置打开个人信息授权？",
                confirmColor: this.themeColor,
                success(res) {
                    if (res.confirm) {
                        uni.openSetting();
                    }
                },
            });
        },
		async handleSubmitInfo(e) {
            const loginData = this.loginData 
            const res = await apiUpdateUser(e, loginData.token);
            this.loginHandle(loginData);
        },
        closePopup() {
            this.showLoginPop = false;
        },
    },
    computed: {
        // 开启手机号注册
        isPhoneRegister() {
            const { register_way } = this.appConfig;
            if (!register_way) {
                return false;
            }
            return register_way.some((item) => item == 1);
        },
        // 开启强制绑定手机号
        isBindMobile() {
            const { coerce_mobile } = this.appConfig;
            return coerce_mobile;
        },
        // 登录方式数组
        loginWay() {
            const { login_way } = this.appConfig;
            if (!login_way) return false;
            this.loginType = login_way[0] || "";
            return login_way;
        },
        // 是否包含对应的登录方式
        hasLoginWay() {
            return (type) => {
                return (
                    this.loginWay && this.loginWay.some((item) => item == type)
                );
            };
        },
        // 开启小程序微信授权
        isMnpWxAuth() {
            const { mnp_wechat_auth } = this.appConfig;
            return mnp_wechat_auth;
        },

        // 开启小程序微信授权
        isOaWxAuth() {
            const { h5_wechat_auth } = this.appConfig;
            return h5_wechat_auth;
        },
        // 开启app微信授权
        isAPPWxAuth() {
            const { app_wechat_auth } = this.appConfig;
            return app_wechat_auth;
        },
        // 开启公众号微信自动登录
        isOaWxAutoLogin() {
            const { h5_auto_wechat_auth } = this.appConfig;
            return h5_auto_wechat_auth;
        },
        // 开启小程序头条登录
        isToutiaoAuth() {
            const { toutiao_auth } = this.appConfig;
            return toutiao_auth;
        },
    },
    onLoad() {
        this.mnpLogin = trottle(this.mnpLogin);
        this.appLogin = trottle(this.appLogin);
        this.getCodeUrl = trottle(this.getCodeUrl);
        this.ttLogin = trottle(this.ttLogin);
        // #ifdef H5
        this.oaAutoLogin();
        // #endif
    },
    onUnload() {},
};
</script>
<style lang="scss">
page {
    background-color: #fff;

    padding: 0;
}

.login {
    height: 100vh;
    padding-top: 80rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;

    .logo {
        height: 126rpx;
        margin-bottom: 40rpx;
    }

    .acount-login,
    .other-login {
        width: calc(100% - 80rpx);

        .input {
            padding-top: 20rpx;
        }

        .login-btn {
            margin: 80rpx 0 50rpx;
            @include background_color();
        }

        .forget-btn {
            border-left: $-solid-border;
        }

        .sms-btn {
            text-align: center;
            border: 1px solid;
            width: 176rpx;
            height: 60rpx;
            line-height: 60rpx;
            border-radius: 60rpx;
            @include font_color();
            @include border_color();
        }

        .wx-login {
            margin-top: 60rpx;

            .image {
                margin-top: 40rpx;
                width: 80rpx;
                height: 80rpx;
            }
        }
    }

    .agreement {
        @include font_color;
    }
}
</style>
